package com.wondersgroup.insurance.dnuilearn.viewgroups.tables;

import android.content.Context;
import android.database.DataSetObserver;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;

import com.wondersgroup.insurance.dnuilearn.R;

import java.util.ArrayList;
import java.util.List;

/**
 * <b>Project:</b> dnuilearn<br>
 * <b>Create Date:</b> 2017/6/8 0008<br>
 * <b>Author:</b> huang saisai <br>
 * <b>Description:</b> <br>
 */
public class TableView extends ViewGroup {
    BaseTableAdapter adapter;
    int curX,curY;
    private int scrollX;
    private int scrollY;

    private int firstRow;
    private int firstColumn;
    private int[] widths;
    private int[] heights;

    @SuppressWarnings("unused")
    private View headView;
    private List<View> rowViewList;
    private List<View> columnViewList;
    private List<List<View>> bodyViewTable;

    private int width;
    private int height;

    private Recycler recycler;

    int rowCount,columnCount;

    boolean needRelayout = false;

    public TableView(Context context) {
        this(context, null);
    }

    public TableView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public TableView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        rowViewList = new ArrayList<>();
        columnViewList = new ArrayList<>();
        bodyViewTable = new ArrayList<>();
        headView = null;


    }

    public Recycler getRecycler() {
        return recycler;
    }

    public void setRecycler(Recycler recycler) {
        this.recycler = recycler;
        scrollX =0 ;
        scrollY = 0;
        firstColumn = 0;
        firstRow = 0;

        requestLayout();

    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        final int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        final int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        final int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        final int heightSize = MeasureSpec.getSize(heightMeasureSpec);

        int w =0,h=0;
        if (adapter != null){
            rowCount = adapter.getRowCount();
            columnCount = adapter.getColmunCount();
            widths = new int[columnCount+1];//所有列 加上左上角的headview
            for(int i=0,size= widths.length;i<size;i++){
                widths[i] = adapter.getWidth(i);
            }
            heights =  new int[rowCount+1];
            for(int i=0,size= heights.length;i<size;i++){
                heights[i] = adapter.getHeight(i);
            }

            if (widthMode == MeasureSpec.AT_MOST){
                w = Math.min(widthSize, sumArray(widths));
            }else if (widthMode == MeasureSpec.UNSPECIFIED){
                w  = sumArray(widths);
            }else {
                w = widthSize;
                int sumWidth = sumArray(widths);
                if (sumWidth < w){
//                    float scale = w/(float)sumWidth;
//                    for (int i = 1; i < widths.length; i++) {
//                        widths[i] = Math.round(widths[i] * scale);
//                    }
//                    widths[0] = widthSize - sumArray(widths, 1, widths.length - 1);
                    int itemWidth = w/widths.length;
                    for (int i=0,size=widths.length;i<size;i++){
                        widths[i] = itemWidth;
                    }
                }
            }

            if (heightMode == MeasureSpec.AT_MOST){
                h = Math.min(heightSize, sumArray(heights));
            }else if (heightMode == MeasureSpec.UNSPECIFIED){
                h  = sumArray(heights);
            }else {
                h = heightSize;
            }


        }else {
            if (heightMode == MeasureSpec.AT_MOST || widthMode == MeasureSpec.UNSPECIFIED) {
                w = 0;
                h = 0;
            } else {
                w = widthSize;
                h = heightSize;
            }
        }
       /* if (firstRow >= rowCount || getMaxScrollY() - getActualScrollY() < 0) {
            firstRow = 0;
            scrollY = Integer.MAX_VALUE;
        }
        if (firstColumn >= columnCount || getMaxScrollX() - getActualScrollX() < 0) {
            firstColumn = 0;
            scrollX = Integer.MAX_VALUE;
        }*/

        setMeasuredDimension(w,h);
    }

    private int sumArray(int array[]) {
        return sumArray(array, 0, array.length);
    }

    private int sumArray(int array[], int firstIndex, int count) {
        int sum = 0;
        count += firstIndex;
        for (int i = firstIndex; i < count; i++) {
            sum += array[i];
        }
        return sum;
    }


    private class BaseTableAdapterDataSetObserver extends DataSetObserver {

        @Override
        public void onChanged() {
            needRelayout = true;
            requestLayout();
        }

        @Override
        public void onInvalidated() {
            // Do nothing
        }
    }
    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        if (needRelayout || changed) {
            needRelayout = false;
            resetTable();
            if (adapter != null){
                width = r - l;
                height = b - t;

                int left, top, right, bottom;
                right = Math.min(width, sumArray(widths));
                bottom = Math.min(height, sumArray(heights));

                //已经绘制了第一个  左上角
                headView = makeAndSetup(-1, -1, 0, 0, widths[0], heights[0]);
                //left不能从0开始
                left = widths[0] - scrollX;
                //填充第一行  橘红色的部分  head 右侧
                for (int i=firstColumn; i<columnCount; i++){
                    right = left+widths[i+1];
                    View v = makeAndSetup(-1,i,left,0,right,heights[0]);
                    rowViewList.add(v);
                    left = right;
                }
                top = heights[0]-scrollY;
                for (int i = firstRow; i <rowCount;i++){
                    bottom = top+heights[i];
                    View v = makeAndSetup(i,-1,0,top,widths[0],bottom);
                    columnViewList.add(v);
                    top = bottom;
                }

                top = heights[0]-scrollY;

                for (int i=firstRow;i<rowCount;i++){
                    left = widths[0] - scrollX;
                    bottom = heights[i+1]+top;
                    List<View> list = new ArrayList<View>();
                    for (int j=firstColumn; j<columnCount;j++){
                        right = left + widths[j+1];
                        final View  body =  makeAndSetup(i,j,left,top,right,bottom);
                        list.add(body);
                        left = right;
                    }
                    top = bottom;

                    bodyViewTable.add(list);
                }
            }
        }
    }

    private View makeAndSetup(int row, int column, int left, int top, int right, int bottom) {
        final View view = obtainView(row, column, right - left, bottom - top);
        view.layout(left, top, right, bottom);
        return view;
    }

    private View obtainView(int row, int colmun, int width, int height) {
        //得到当前控件的类型
        int itemType=adapter.getItemViewType(row,colmun);
        //从回收池 拿到一个View==null
        View reclyView=recycler.getRecyclerdView(itemType);
        //reclyView 可能为空
        View view=adapter.getView(row,colmun,reclyView,this);
        if (view == null) {
            throw new RuntimeException("view  不能为空");
        }
        //View不可能为空
        view.setTag(R.id.tag_type_view,itemType);
        view.setTag(R.id.tag_column,colmun);
        view.setTag(R.id.tag_row,row);
        view.measure(MeasureSpec.makeMeasureSpec(width,MeasureSpec.EXACTLY),MeasureSpec.makeMeasureSpec(height,MeasureSpec.EXACTLY));
        addTableView(view,row,colmun);
        return view;
    }
    private void addTableView(View view, int row, int column) {
        if (row == -1 && column == -1) {
            addView(view, getChildCount() -1);
        } else if (row == -1 || column == -1) {
            addView(view, getChildCount() - 2);
        } else {
            addView(view, 0);
        }
    }

    private void resetTable() {
        headView = null;
        rowViewList.clear();
        columnViewList.clear();
        bodyViewTable.clear();

        removeAllViews();
    }

    /**
     * Returns the adapter currently associated with this widget.
     *
     * @return The adapter used to provide this view's content.
     */
    public BaseTableAdapter getAdapter() {
        return adapter;
    }

    /**
     * Sets the data behind this TableFixHeaders.
     *
     * @param adapter
     *            The BaseTableAdapter which is responsible for maintaining the data
     *            backing this list and for producing a view to represent an
     *            item in that data set.
     */
    public void setAdapter(BaseTableAdapter adapter) {
        this.adapter = adapter;
        adpterDataSetObserver = new BaseTableAdapterDataSetObserver();
        this.recycler = new Recycler(adapter.getViewTypeCount());

        scrollX = 0;
        scrollY = 0;
        firstColumn = 0;
        firstRow = 0;

        needRelayout = true;
        requestLayout();


    }

    BaseTableAdapterDataSetObserver  adpterDataSetObserver;
}
